package com.example.calculatorautomation

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo

class MyAccessibilityService : AccessibilityService() {
    companion object {
        private var instance: MyAccessibilityService? = null
        private var pendingFormula: String? = null

        fun enqueueFormula(formula: String) {
            Log.d("CalcDemo", "enqueueFormula: $formula")
            pendingFormula = formula
            instance?.processFormula()
        }
    }

    override fun onCreate() {
        super.onCreate()
        Log.d("CalcDemo", "MyAccessibilityService onCreate")
    }

    override fun onServiceConnected() {
        super.onServiceConnected()
        instance = this
        Log.d("CalcDemo", "无障碍服务已连接")
        serviceInfo = serviceInfo.apply {
            eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED or AccessibilityEvent.TYPE_VIEW_CLICKED
            feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
            flags = AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS
        }
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        Log.d("CalcDemo", "onAccessibilityEvent: $event")
        if (event?.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            val pkg = event.packageName?.toString()
            Log.d("CalcDemo", "窗口变化: $pkg")
            if (pkg?.contains("calculator", ignoreCase = true) == true ||
                pkg?.contains("honor", ignoreCase = true) == true) {
                processFormula()
            }
        }
    }

    override fun onInterrupt() {
        Log.d("CalcDemo", "无障碍服务被中断")
    }

    private fun launchCalculator() {
        try {
            val intent = Intent()
            intent.setClassName("com.hihonor.calculator", "com.hihonor.calculator.Calculator")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
            Log.d("CalcDemo", "已尝试启动荣耀计算器")
        } catch (e: Exception) {
            Log.e("CalcDemo", "启动计算器失败: ${e.message}")
        }
    }

    fun processFormula() {
        val formula = pendingFormula ?: return
        pendingFormula = null
        Log.d("CalcDemo", "开始处理公式: $formula")
        launchCalculator()
        Handler(Looper.getMainLooper()).postDelayed({
            inputFormula(formula)
        }, 1200)
    }

    private fun inputFormula(formula: String) {
        val root = rootInActiveWindow
        if (root == null) {
            Log.e("CalcDemo", "无法获取当前窗口节点")
            return
        }
        Log.d("CalcDemo", "开始输入公式")

        // 递归遍历所有节点，打印详细信息和actions
        fun logAllNodes(node: AccessibilityNodeInfo?, depth: Int = 0) {
            if (node == null) return
            val prefix = "  ".repeat(depth)
            val cls = node.className?.toString() ?: ""
            val txt = node.text?.let { "\"$it\"" } ?: "null"
            val resId = node.viewIdResourceName ?: ""
            val desc = node.contentDescription?.toString() ?: ""
            val actions = node.actionList?.joinToString { it.label?.toString() ?: it.id.toString() } ?: ""
            Log.d(
                "CalcDemo",
                "${prefix}Node: class=$cls, text=$txt, resId=$resId, desc=$desc, editable=${node.isEditable}, childCount=${node.childCount}, actions=[$actions]"
            )
            for (i in 0 until node.childCount) {
                logAllNodes(node.getChild(i), depth + 1)
            }
        }
        logAllNodes(root)

        // 只做按钮点击，不做结果验证
        for (ch in formula) {
            val btnNode = when (ch) {
                '0','1','2','3','4','5','6','7','8','9','.' -> {
                    root.findAccessibilityNodeInfosByText(ch.toString()).firstOrNull {
                        it.className?.toString()?.contains("Button") == true
                    }
                }
                '+' -> findNodeByResId(root, "com.hihonor.calculator:id/op_add")
                '-' -> findNodeByResId(root, "com.hihonor.calculator:id/op_sub")
                '*', 'x', 'X' -> findNodeByResId(root, "com.hihonor.calculator:id/op_mul")
                '/' -> findNodeByResId(root, "com.hihonor.calculator:id/op_div")
                else -> null
            }
            if (btnNode != null) {
                btnNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                Thread.sleep(200)
                Log.d("CalcDemo", "点击按钮: $ch")
            } else {
                Log.e("CalcDemo", "未找到按钮: $ch")
            }
        }
        // 点击等号
        val eqNode = findNodeByResId(root, "com.hihonor.calculator:id/eq")
        if (eqNode != null) {
            eqNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            Log.d("CalcDemo", "点击等号")
        } else {
            Log.e("CalcDemo", "未找到等号按钮")
        }
    }

    private fun findNodeByResId(node: AccessibilityNodeInfo, resId: String): AccessibilityNodeInfo? {
        if (node.viewIdResourceName == resId) return node
        for (i in 0 until node.childCount) {
            val child = node.getChild(i) ?: continue
            val result = findNodeByResId(child, resId)
            if (result != null) return result
        }
        return null
    }
}
